import fg from 'fast-glob';
import fs from "fs-extra";
import path from "path";
import { TaskResult } from "../../common/tasks/BastTask.js";
import { toolchain } from "../../toolchain.js";
import { Mangler } from "../../tools/Mangler.js";
import { WebGLEnv } from "../WebGLEnv.js";
import { WebGLProcessJsTask } from "./WebGLPostBuildUnityTask.js";
import { CommonEnv } from '../../common/CommonEnv.js';
import { replaceInFileOrThrow } from '../../tools/vendor.js';

export class WebGLDouyinJsTask extends WebGLProcessJsTask {
    async run(): Promise<TaskResult<void>> {
        // 抖音js文件需放在Assets\StreamingAssets\__cp_js_files
        const jsRoot = path.join(toolchain.params.workSpacePath, WebGLEnv.DouyinJsRoot);
        await fs.ensureDir(jsRoot);
        // 先清理旧的js，因可能不重新打包，这样老的js会留着，这里先删掉
        const oldJss = await fg('*.js', { cwd: jsRoot });
        for (const js of oldJss) {
            await fs.unlink(path.join(jsRoot, js));
        }

        // 修改UnityApplication.js
        const ua = path.join(toolchain.params.workSpacePath, CommonEnv.TsOutput, 'System/UnityApplication.js');
        await replaceInFileOrThrow(ua, 'UnityApplication.IsDouyin = false', 'UnityApplication.IsDouyin = true');

        // 处理JS
        await this.processJSFiles(WebGLEnv.DouyinJsRoot, 'buildForBrowser');
        
        // mangle js files
        const reservedFile = path.join(toolchain.params.workSpacePath, WebGLEnv.MangleReserved);
        const cacheFile = path.join(toolchain.params.workSpacePath, WebGLEnv.MangleCache);
        // 先提取reserved字段
        const reserved = await toolchain.filterPuertsReserved.readAll(toolchain.params.workSpacePath, reservedFile);
        const mangler = new Mangler();
        // Brower版本puerts将所有js文件以map形式保存，terser无法获取类之间的关联，故不能混淆properties
        await mangler.beginMangle(reserved, cacheFile, true, false);
        const puertsRuntimeJs = path.join(jsRoot, WebGLEnv.PuertsRuntimeJs);
        const puertsBrowserJsResourcesJs = path.join(jsRoot, WebGLEnv.PuertsBrowserJsResourcesJs);
        // 先备份
        await fs.copy(puertsRuntimeJs, path.join(toolchain.params.workSpacePath, WebGLEnv.MangleBak, WebGLEnv.PuertsRuntimeJs));
        await fs.copy(puertsBrowserJsResourcesJs, path.join(toolchain.params.workSpacePath, WebGLEnv.MangleBak, WebGLEnv.PuertsBrowserJsResourcesJs));
        await mangler.mangleOneJs(puertsRuntimeJs, puertsRuntimeJs);
        await mangler.mangleOneJs(puertsBrowserJsResourcesJs, puertsBrowserJsResourcesJs);
        await mangler.patchJs(puertsBrowserJsResourcesJs);
        await mangler.endMangle(cacheFile);

        // 复制到Assets\StreamingAssets\__cp_js_files
        await fs.copyFile(puertsRuntimeJs, path.join(jsRoot, WebGLEnv.PuertsRuntimeJs));
        await fs.copyFile(puertsBrowserJsResourcesJs, path.join(jsRoot, WebGLEnv.PuertsBrowserJsResourcesJs));

        return { success: true, errorCode: 0, data: void 0 };
    }
}
